/**
 * Created by zjx on 2017/1/16.
 */
!function init(){
    $('.multi-upload-portlet').each( function( idx , elem ){
        initMultiUpload( $(elem) );
    });
}();

function initMultiUpload( $portlet ){

    var csrf_token = $('#csrfToken').text();
    
    var $form = $portlet.find('.upload-form');

    var $product_selector = $portlet.find('.product-selection');

    var $sort_btn = $portlet.find('.sort-btn');
    
    var $upload_all_btn = $portlet.find('.upload-all-btn');

    var upload_img_count = 0;
    
    var start_uploading = false;
    
    // multi upload
    $form.fileupload({
        url: $form.attr('action')
    });

    $form
        .bind('fileuploadsubmit', function (e, data) {
            if ( !  $product_selector.val() ) {
                alert('请先选择产品');
                return false;
            }

            data.formData = {
                url : $form.attr('action'),
                _token: csrf_token,
                product_id: $product_selector.val()
            };
        })
        .bind('fileuploadsend', function ( e, data ) {
            App.blockUI($('.portlet'));
        })
        .bind('fileuploaddone', function ( e, data ) {
            App.unblockUI($('.portlet'));
            upload_img_count--;
            if ( ! upload_img_count ) {
                setTimeout(function(){
                    $sort_btn.trigger('click');
                    start_uploading = false;
                },1000);
            }
        });

    $upload_all_btn.on('click',function(){
        upload_img_count = 0;
        $form.find('tr').each( function( index , tr ) {
            if ( ! tr.dataset.key ) {
                upload_img_count++;
            }
        });
    });

    $product_selector.on('change' , function(){

        var product_id = $(this).val();
        $form.find('tbody').empty();
        $sort_btn.hide();

        if ( ! product_id ) return false;

        App.blockUI($('.portlet'));
        $.ajax({
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            url: $form.fileupload('option', 'url') + '/' + product_id,
            dataType: 'json',
            context: $form[0]
        })
        .done(function (result) {
            if ( result.length ) $sort_btn.show();

            $(this).fileupload('option', 'done')
                .call(this, null, {
                    result: { files : result }
                });
        })
        .always(function(){
            App.unblockUI($('.portlet'));
        });

    });
    
    
    // sort 
    var $nest_wrapper = $portlet.find('.nestable-list');

    $nest_wrapper.sortable({
        revert: true
    });

    $sort_btn.on('click',function updateImageSort(){

        var sorted_key_arr = [];

        $nest_wrapper.find('tr').each(function( index , tr) {
            sorted_key_arr.push( tr.dataset.key );
        });

        $.ajax({
            method: "POST",
            url: $form.attr('action') + '/' + $product_selector.val(),
            dataType: 'json',
            data: {
                _method : 'PATCH',
                _token : csrf_token,
                sorted_arr : sorted_key_arr
            }
        })
            .done(function(res){
                alert( res.error );
            })
            .fail(function(err){
                console.log('更新失败');
            })

    });

}